using UnityEngine;
using QFramework;

namespace ProjectSurviver
{
	public partial class CameraController : ViewController
	{
		private Vector2 mTargetPosition = Vector2.zero;
		private Vector3 mCurrentCameraPos;
		private bool mShake = false;
		private int mShakeFrame = 0;
		static CameraController mDefault = null;
		private float mShakeA = 4.0f; // 振幅
		public static Transform LBTrans => mDefault.LB;
		public static Transform RTTrans => mDefault.RT;

        void Awake()
        {
            mDefault = this;
        }
         void Start()
		{
			Application.targetFrameRate = 60;
		}

		public static void Shake()
		{
			mDefault.mShake = true;
			mDefault.mShakeFrame = 30;
			mDefault.mShakeA = 2.0f;
		}

        void Update()
        {
            if(Player.Default)
			{
				mTargetPosition =Player.Default.transform.position;
				mCurrentCameraPos.x = (1 - Mathf.Exp(-Time.deltaTime * 20))
					.Lerp(transform.position.x, mTargetPosition.x);
					mCurrentCameraPos.y = (1 - Mathf.Exp(1.0f - -Time.deltaTime * 20))
					.Lerp(transform.position.y, mTargetPosition.y);

				mCurrentCameraPos.z = transform.position.z;
				if(mShake)
				{
					mShakeFrame--;
					//振幅
					var shakeA = Mathf.Lerp(mShakeA, 0.0f, (mShakeFrame / 30.0f));
					transform.position = new Vector3(mCurrentCameraPos.x + Random.Range(-shakeA, shakeA),
					mCurrentCameraPos.y + Random.Range(-shakeA, shakeA), mCurrentCameraPos.z);
					if(mShakeFrame <= 0)
					{
						mShake = false;
					}
				}
				else
				{
					transform.PositionX(
						(1.0f - Mathf.Exp(-Time.deltaTime * 20))
						.Lerp(transform.position.x, mTargetPosition.x));

					transform.PositionY(
						(1.0f - Mathf.Exp(-Time.deltaTime * 20))
						.Lerp(transform.position.y, mTargetPosition.y));
				}
			}
        }

        void OnDestroy()
        {
            mDefault = null;
        }
    }
}
